package com.gitee.wsl.doc.prosemirror.model.node.ext

import com.gitee.wsl.doc.prosemirror.model.mark.MarkType
import com.gitee.wsl.doc.prosemirror.model.node.Node


fun Node.getMarkLocation(pos: Int, markType: MarkType): Pair<Int, Int>? {
    val doc = this
    val pos = doc.resolve(pos)

    val start = pos.parent.childAfter(pos.parentOffset)
    if (start.node == null) {
        return null
    }

    val mark = start.node.marks.find { it.type == markType }
    if (mark == null) {
        return null
    }

    var startIndex = pos.index()
    var startPos = pos.start() + start.offset

    while (startIndex > 0 && mark.isInSet(pos.parent.child(startIndex - 1).marks)) {
        startIndex -= 1
        startPos -= pos.parent.child(startIndex).nodeSize
    }

    var endIndex = pos.indexAfter()
    var endPos = startPos + start.node.nodeSize

    while (endIndex < pos.parent.childCount && mark.isInSet(pos.parent.child(endIndex).marks)) {
        endPos += pos.parent.child(endIndex).nodeSize
        endIndex += 1
    }

    return startPos to endPos
}